package com.xgkj.diyiketang.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.xgkj.diyiketang.activity.NewFriendActivity;
import com.xgkj.diyiketang.activity.RecommendAlumnusActivity;
import com.xgkj.diyiketang.activity.SearchChiBanActivity;
import com.xgkj.diyiketang.activity.data.FriendAdapter;
import com.xgkj.diyiketang.activity.data.RecommendFriendAdapter;
import com.xgkj.diyiketang.task.AddFriendTask;
import com.xgkj.diyiketang.task.DeleteFriendsTask;
import com.xgkj.diyiketang.task.StudentListTask;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrater on 2015/12/8.
 */
public class TuiJianFragment extends BaseFragment implements View.OnClickListener, PullToRefreshListView.OnRefreshListener, PullToRefreshListView.OnLoadDataListener {
    private Context mContext;
    private PullToRefreshListView mListView;
    private FriendAdapter mAdapter;
    private int currentPage = 1;
    private int size = 30;
    private int mTuijianListTaskId = -1;
    private ImageView sousuo;
    private View view;
    private LinearLayout gridviewLayout;
    private GridView recommendList;
    private TextView changeFriends;
    private int recommendTaskId = -1;
    private RecommendFriendAdapter recommendFriendAdapter;
    private RelativeLayout newFriendLayout;
    private RelativeLayout recommendalumnus;
    private int addFriendTaskId = -1;
    private int deleteFriendTaskId = -1;
    private View line;

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.tuijianfragment, null);
            mContext = getActivity();
            initView(view);
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        isShow = true;

        return view;
    }

    private void initView(View view) {
        sousuo = (ImageView) view.findViewById(R.id.search);
        sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, SearchChiBanActivity.class));
            }
        });
//        gridviewLayout = (LinearLayout) view.findViewById(R.id.gridview_layout);
//        gridviewLayout.setVisibility(View.GONE);
//        recommendList = (GridView) view.findViewById(R.id.recommend_list);
        recommendFriendAdapter = new RecommendFriendAdapter(mContext);
//        recommendList.setAdapter(recommendFriendAdapter);
//        changeFriends = (TextView) view.findViewById(R.id.change_friends);
//        changeFriends.setOnClickListener(this);
        newFriendLayout = (RelativeLayout) view.findViewById(R.id.newfriend_layout);
        recommendalumnus = (RelativeLayout) view.findViewById(R.id.recommend_alumnus_layout);
        line =view.findViewById(R.id.line);
        newFriendLayout.setOnClickListener(this);
        recommendalumnus.setOnClickListener(this);
//        view.findViewById(R.id.add_friend).setOnClickListener(this);
        mListView = (PullToRefreshListView) view.findViewById(R.id.tuijian_list);
        mListView.init(mContext, true);
        mListView.setOnCreateContextMenuListener(this);
        registerForContextMenu(mListView);
        mAdapter = new FriendAdapter(mContext);
        mListView.setAdapter(mAdapter, false);
        mListView.setOnRefreshListener(this);
        mListView.setOnLoadDataListener(this);
        mListView.doRefresh();
//        View v= view.findViewById(R.id.content_layout);
//        NoDataUtil noDataUtil = new NoDataUtil(mContext,v);
//        noDataUtil.ListViewEmpty(mListView,null,null,-1);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.add_friend:
//                List<String> userList = recommendFriendAdapter.getCheckedUser();
//                for (int i = 0; i < userList.size(); i++) {
//                    String userId = userList.get(i);
//                    if (i == userList.size() - 1) {
//                        addFriend(userId, true);
//                    } else {
//                        addFriend(userId, false);
//                    }
//                }
//                break;
//            case R.id.change_friends:
//                recommendFriendAdapter.cleanCheckedUser();
//                getRecommendFriend();
//                break;
            case R.id.newfriend_layout:
                Intent new_friden_intent = new Intent(mContext, NewFriendActivity.class);
                startActivity(new_friden_intent);
                break;
            case R.id.recommend_alumnus_layout:
                Intent recommend_alumns_intent = new Intent(mContext, RecommendAlumnusActivity.class);
                startActivity(recommend_alumns_intent);
                break;
        }
    }

    private boolean isShow;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isShow = true;
            if (mAdapter != null) {
                mListView.doRefresh();
            }
        } else {
            isShow = false;
        }
    }

    private void getRecommendFriend() {
        StudentListTask task = new StudentListTask(9, 1, 1);
        task.addListener(new MyListener(mContext));
        recommendTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void addFriend(String userId, boolean isEnd) {
        AddFriendTask task = new AddFriendTask(userId);
        task.addListener(new MyListener(mContext));
        if (isEnd) {
            addFriendTaskId = getEatShowApp().getTaskManager().addTask(task);
        } else {
            getEatShowApp().getTaskManager().addTask(task);
        }
    }

    private void getTuijianList() {
        if (mTuijianListTaskId != -1) {
            return;
        }
        if (currentPage == 0) {
            mListView.setNoNextPage();
            return;
        }
        StudentListTask task = new StudentListTask(size, currentPage, 0);
        task.addListener(new MyListener(mContext));
        mTuijianListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class MyListener extends ShowToastTaskEventListener {
        public MyListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == mTuijianListTaskId) {
                mTuijianListTaskId = -1;
                if (currentPage == 1) {
                    mAdapter.clearData();
                    mListView.onRefreshComplete();
                    mListView.enableLoadMore();
                } else {
                    mListView.onLoadDataComplete(true);
                }
                List<EatShowUserInfo> fansList = new ArrayList<EatShowUserInfo>();
                if (data != null) {
                    fansList = (List<EatShowUserInfo>) data;
                }

                if (fansList != null && fansList.size() > 0) {
                    mAdapter.updateData(fansList);
                }
                if (mAdapter.getCount() < 1) {
                    mListView.setVisibility(View.GONE);
                    getRecommendFriend();
                    line.setVisibility(View.VISIBLE);
                    newFriendLayout.setVisibility(View.VISIBLE);
                    recommendalumnus.setVisibility(View.VISIBLE);
                } else {
                    line.setVisibility(View.INVISIBLE);
                    newFriendLayout.setVisibility(View.INVISIBLE);
                    recommendalumnus.setVisibility(View.INVISIBLE);
                    mListView.setVisibility(View.VISIBLE);
                }
                currentPage = result;

            } else if (taskId == recommendTaskId) {
                List<EatShowUserInfo> fansList = new ArrayList<EatShowUserInfo>();
                if (data != null) {
                    fansList = (List<EatShowUserInfo>) data;
                }
                recommendFriendAdapter.clearData();
                recommendFriendAdapter.updateData(fansList);
            } else if (taskId == addFriendTaskId) {
                ToastUtil.showMessage(mContext, R.string.apply_to_friend_alreay_send);
            } else if (taskId == deleteFriendTaskId) {
                currentPage = 1;
                getTuijianList();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == mTuijianListTaskId) {
                mTuijianListTaskId = -1;
                if (currentPage == 1) {
                    mListView.onRefreshComplete();
                } else {
                    mListView.onLoadDataComplete(false);
                }
            } else if (taskId == recommendTaskId) {

            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    @Override
    public void onPullRefresh() {

    }

    @Override
    public void onLoadMore() {
        getTuijianList();
    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        getTuijianList();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("TuijianFragment");
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("TuijianFragment");
        if (isShow) {
            if (mAdapter != null) {
                mListView.doRefresh();
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        int position = info.position;
        if (mListView.getHeaderViewsCount() > 0) {
            position--;
        }
        if (position < 1 || position >= mAdapter.getCount()) return;
        menu.setHeaderTitle(R.string.prompt);
        menu.add(0, 0, 0, R.string.delete);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        if (mListView.getHeaderViewsCount() > 0) {
            position--;
        }

        if (position < 1 || position >= mAdapter.getCount()) return false;
        if (item.getItemId() == 0) {
            EatShowUserInfo cinfo = (EatShowUserInfo) mAdapter.getItem(position);
            if (cinfo != null) {
                deleteFriend(cinfo.getUserId());
            }
        }

        return super.onContextItemSelected(item);
    }

    private void deleteFriend(String userId) {
        DeleteFriendsTask task = new DeleteFriendsTask(userId);
        task.addListener(new MyListener(mContext));
        deleteFriendTaskId = getEatShowApp().getTaskManager().addTask(task);
    }
}
